// pages/agentPayLaunch/agentPayLaunch.js
var app = getApp();
var bg_pic= 'https://qn.youheone.com/5dca620200811175348206.png';
var save_path= '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    order_id:'',//订单ID
    type:'',//代付类型1：订单代付 2:续费代付 3.工单代付
    orderInfo:{},//订单详情
    engineersInfo:{},//工程详情
    order_no:'',//订单编号
    order_actual_money:'',//订单金额
    create_time:'',//下单时间
    shareBox:false

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //type说明： 1订单代付 2续费代付
    this.setData({
      order_id:options.order_id,
      type:options.type,//1：订单代付 2:续费代付
    })
    if(this.data.type==1){
      this.getOrderInfo();//订单详情
    }else if(this.data.type==2){
      this.getRenewOrderInfo();
    }else if(this.data.type==3){
      this.getWorkOrderDetail();
    }
    this.getEngMsg();
    
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },



  /**
   * 用户点击右上角分享
   */

   // 查询续费订单详情
 getRenewOrderInfo: function () {
  var that = this;
  var order_id = that.data.order_id;  // 订单ID
  app.ajax({
    url: 'Engineer/Renew/getRenewOrderDetail',
    data: { renew_order_id: order_id },
    success: function (res) {
      if (res.data.code == 1000) {
        that.setData({
          orderInfo: res.data.data,
          order_no:res.data.data.renew_order_no,
          order_actual_money:res.data.data.order_actual_money,
          create_time:res.data.data.create_time
        });
      } else {
        app.showToast(res.data.message);
      }
      console.log('订单详情',res);
    }
  })
},
  //查询订单详情
  getOrderInfo:function(){
    var that = this;
    var order_id = that.data.order_id;
    app.ajax({
      url: 'User/Order/getOrderDetail',
      method: "POST",
      data: { order_id: order_id },
      success: function (res) {
        //console.log(res)
        if (res.data.code == 1000) {
          that.setData({
            orderInfo: res.data.data,
            order_no:res.data.data.order_no,
            order_actual_money:res.data.data.order_actual_money,
            create_time:res.data.data.create_time
          });
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
   // 工单详情
   getWorkOrderDetail: function(){
    var that = this;
    var id = that.data.order_id;
    app.ajax({
      url: 'Engineer/Workorder/workOrderDetail',  
      data: { work_order_id: id},
      success: function(res){
        that.setData({
          order_no:res.data.data.order_number,
          order_actual_money:res.data.data.combo_money,
          create_time:res.data.data.order_time
        });
       

      }
    })

  },
    // 获取用户信息
  getEngMsg: function(){
    var that = this;
    app.ajax({
      url: "Engineer/Engineers/engineersInfo",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            engineersInfo: res.data.data
          })
        } else {
          that.setData({
            engineersInfo:''            
          })
        }
      }
    })
  },
   //生成页面二维码pages/shopping/goodsDetail/goodsDetail
   getQr() {
    var that = this;
    //pages/agentPay/agentPay
    app.createQrcode('order_id=' + that.data.order_id + "&uid="+that.data.engineersInfo.engineers_id+"&type="+that.data.type+"&r=5", 'pages/agentPay/agentPay', function(url) {
      console.log(url)
      wx.downloadFile({
        url: url,
        success: function(res) {
          // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
          if (res.statusCode === 200) {
            that.setData({
              qrcode: res.tempFilePath
            })
            that.getShareCanvas();
          }
        }
      })
    });
  },

  //生成canvas
  getShareCanvas() {
    var that = this;
    that.setData({
      shareBox:true
    })
    //console.log(bg_pic)
    //var main_pic = that.data.shareBg;
    var main_pic = that.data.qrcode;
    //console.log(main_pic);
    wx.getImageInfo({
      src: main_pic,
      success: function(res) {
        //console.log(res)
        //console.log(res.width)
        //console.log(res.height)
        const ctx = wx.createCanvasContext('shareCanvas');
        ctx.clearRect(0, 0, 0, 0);
        const WIDTH = Number(wx.getSystemInfoSync().windowWidth) * 0.7;
        const HEIGHT = WIDTH * 1.4;
        const left_height = HEIGHT - WIDTH //canvas除图片外的高度
        const btn_h = Number(wx.getSystemInfoSync().windowHeight);
        const code_width = left_height - 20 //二维码宽度
        that.setData({
          canvas_w: WIDTH,
          canvas_h: HEIGHT,
          btn_h: btn_h,
        })
        bg_pic = res.path
        ctx.fillStyle='white';
        ctx.fillRect(0, 0, WIDTH, HEIGHT)
        ctx.drawImage(bg_pic,  WIDTH*0.2, 40, WIDTH*0.6, WIDTH*0.6);
        //console.log(code_width/6)

        var size = 10;
        var boxWidth = WIDTH;
        var initHeight = WIDTH-40;
        var height_line = 20;
        var str = '扫一扫识别二维码代付';
  
        fillAllText(ctx, str, initHeight, WIDTH, 12, '#6da9ff', WIDTH*0.45, 1, height_line, 'middle')

        initHeight += height_line*1.5;
        var tips = '需付款:'+that.data.order_actual_money;
        var sum = 0;
        fillAllText(ctx, tips, initHeight, boxWidth, 18, '#c80000', WIDTH*0.45, 1, height_line, 'middle')

        initHeight += height_line*1.5;
        //console.log(initHeight)
        var str = '"'+that.data.engineersInfo.engineers_name+"' 向您发起了代付";
        fillAllText(ctx, str, initHeight, boxWidth, 12, '#333333', WIDTH*0.45, 2, initHeight, 'middle')

        initHeight += height_line;
        var str = '订单编号:'+that.data.order_no;
        fillAllText(ctx, str, initHeight, boxWidth, 12, '#333333', WIDTH*0.45, 1, height_line*1.5, 'middle')
 
        const metrics = ctx.measureText(str)

        const metrics1 = ctx.measureText(str)
        ctx.beginPath()
        ctx.moveTo(metrics.width + 20, initHeight)
        ctx.lineTo(metrics1.width + metrics.width + 20, initHeight)
    
        ctx.draw();
        //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
        setTimeout(function() {
          wx.canvasToTempFilePath({
            canvasId: 'shareCanvas',
            success: function(res) {
              wx.hideLoading()
              var tempFilePath = res.tempFilePath;
              save_path= res.tempFilePath
            },
            fail: function(res) {
              //console.log(res);
            }
          });
        }, 500);
      }
    })

    function fillAllText(ctx, str, initHeight, boxWidth, size, color, offset, l, height_line, line) {
      /*
      ctx:canvas实例
      str:text字符串
      initHeight:位置高度
      boxWidth:文本大小
      size:字体大小
      color:字体颜色
      offset:字体偏移量
      l:显示行数
      */
      //console.log('initHeight:'+initHeight)
      console.log('字体大小',size);
      ctx.font=size+'px serif';
      ctx.fillStyle=color;
      ctx.textAlign = 'center';
      ctx.setTextBaseline(line)
      var lineWidth = 0; //字符串长度
      var lastSubStrIndex = 0;
      var h = 1;
      for (let i = 0; i < str.length; i++) {
        lineWidth += ctx.measureText(str[i]).width;
        if (h < l + 1) {
          if (lineWidth > boxWidth) {
            if (h == l) {
              var str = str.substring(0, i - 3) + '...';
            }
            ctx.fillText(str.substring(lastSubStrIndex, i), 10 + offset, initHeight); //绘制截取部分
            initHeight += height_line + 0; //20为字体的高度
            lineWidth = 0;
            lastSubStrIndex = i;
            h++;
          }
          if (i == str.length - 1) {
            //绘制剩余部分
            ctx.fillText(str.substring(lastSubStrIndex, i + 1), 10 + offset, initHeight);
            h++;
          }
        }
      }
    }
  },
  //保存二维码
  saveCode: function() {
    wx.saveImageToPhotosAlbum({
      filePath: save_path,
      success(res) {
        //console.log(res)
        app.showToast('图片保存成功');
        wx.navigateBack({
          delta: 1
        })
      }
    })
    // wx.downloadFile({
    //   url: '', //仅为示例，并非真实的资源
    //   success: function (res) {
    //     // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
    //     if (res.statusCode === 200) {
    //       wx.saveImageToPhotosAlbum({
    //         filePath: res.tempFilePath,
    //         success: function (res) {
    //           console.log(res)
    //         },
    //         fail: function (res) {
    //           console.log(res)
    //           console.log('fail')
    //         }
    //       })
    //     }
    //   },
    //   fail: function (res) {
    //     console.log(res)
    //     console.log('fail')
    //   }
    // })

  },
})